/**
 * (C) 2007 - Boston University
 * 	Contact: Michael Ocean 

  This work is a part of the larger snBench project.  Information
  can be found at: http://csr.bu.edu/snbench

  This program is free software; you can redistribute it and/or
  modify it under the terms of Version 2 of the GNU General Public 
  License.
  
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**/
package snbenchlib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;

import step.Node;

public class Util {

	/**
	 * Returns all folders/files in path specified by uri_in after
	 * the given uri_base.  
	 * 
	 * @param uri_in - The URI to be split
	 * @param uri_base - The base URI (to be ignored)
	 * 
	 * @return array of strings or null if uri_in does not start with uri_base.
	 * 
	 * e.g.,
	 * 
	 * URISplitter("www.google.com/this/that/other","www.google.com/")
	 * 	returns [this,that,other]
	 * 
	 * URISplitter("www.google.com/this/r/","www.google.com/")
	 * 	returns [this,r]
	 * 
	 * URISplitter("www.google.com/this/r/",".com/")
	 * 	returns null
	 * 
	 */
	public static String[] URISplitter(String uri_in, String uri_base){
		if(!uri_in.startsWith(uri_base))
			return null;
		
		String uril = uri_in.substring(uri_base.length());
		return uril.split("/");
	}
	
	/**
	 * @param s a string to be split.
	 * @return ArrayList of Strings taken from s where space is
	 * 		the delimiter but quoted strings are not broken. 
	 */
	public static ArrayList<String> StringSplitter(String s){
		ArrayList<String> al = new ArrayList<String>();
		
		java.util.regex.Pattern p =
			java.util.regex.Pattern.compile("([^\"]*)\"| ?([^ ]+) ?") ;
		
			//System.out.println("splitting: '" + s + "'") ;
			java.util.regex.Matcher m = p.matcher(s) ;
			while(m.find()) {
				for(int i=0; i<m.groupCount(); ++i) {
					String sTemp = m.group(i+1) ;
					if(null!=sTemp) {
						sTemp = sTemp.trim();
						//System.out.println(" found: '" + sTemp + "'") ;
						al.add(sTemp);
					}
				}
			}
		
		return al;
	}
	
	/**
	 * Return the string s with quotes around it if it
	 * contains a space
	 * @param s
	 * 
	 * @return
	 */
	public String requoteIfNeeded(String s){
		if(s.contains(" "))
			return "\"" + s + "\"";
		return s; 
	}

	
	
	/** for testing -- do not use **/
	private static BufferedReader br;

	private static String getcmd() {
		System.out.print(":");
		
		try{
			return br.readLine().replace("\n","").replace("\r","");
		}catch(IOException io){
			io.printStackTrace();
			return "quit";
		}
	}

	static public void main(String args[]) {		
		boolean bRunning = true;
		br = new BufferedReader(new InputStreamReader(System.in));
		
		while(bRunning){
			String sCmd = getcmd();
			System.out.println("Got [" + sCmd + "]");
			
			if(sCmd.equalsIgnoreCase("quit")){
				bRunning=false;
			}
			else
			{
				ArrayList<String> al = StringSplitter(sCmd);
			}
		}
		
	}
	
	static public String currentTime(){
		Calendar c = Calendar.getInstance();
	    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy\th:mm:ss a");
		return formatter.format(c.getTime());
	}

	static public String formatTime(long milliTime){
	    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy\th:mm:ss a");
		return formatter.format(milliTime);
	}

	
	/**
	 * Populates a Hashtable from arguments of the form 
	 * 		--key value
	 * Where value will be either an
	 *  Integer if the value can be formatted as a number,
	 *  Boolean if matches "true" or "false" (case independent)
	 *  String otherwise 
	 * 
	 * If no value is specified (e.g., this is the last arg in the
	 * list or is in the list as --key1 --key2 ...) key1 is assumed
	 * to be boolean with value true. 
	 * 
	 * @param args
	 * @return a populated Hashtable object as described above
	 */
	static public Hashtable<String,Object> parseArgs(String args[]){
		Hashtable<String,Object> config = new Hashtable<String,Object>();
		String sKey, sValue;
		
		for(int i=0;i<args.length;i++){
			String s = args[i];
			if(s.startsWith("--")){
				sKey = s.substring(2);
				if(i==args.length-1){
					config.put(sKey, new Boolean(true));
				}
				else if(args[i+1].startsWith("--"))
					config.put(sKey, new Boolean(true));
				else{
					// get the value
					sValue = args[i+1];
					try{
						Integer num = Integer.valueOf(sValue);
						config.put(sKey, num);
					}catch(NumberFormatException e){
						if(sValue.equalsIgnoreCase("true")||sValue.equalsIgnoreCase("false")){
							Boolean bol = Boolean.valueOf(sValue);
							config.put(sKey, bol);
						}else{
							config.put(sKey, sValue);
						}
					}					
					i++;
				}
			}
			else
				System.err.println("WARNING: Bad/misplaced argument '" + s + "' has been ignored.");
		}
		return config;
	}

	public static void DebugHashTable(Hashtable<String,?> ht) {
		System.out.println("Printing Hashtable of length " + ht.size());
		System.out.println("Node ID\t\t\tType");
		System.out.println("--------------------------------------------------");
		for(String s:ht.keySet()){
			System.out.println(s + "\t\t\t" + ht.get(s).toString());
		}
		System.out.println("==================================================");
	}
	
    public static int findInArray(String ID, Node array[]){
    	if(array==null)
    		return -1;
    	for(int i=0;i<array.length;i++){
    		if(array[i].GetID().equals(ID))
    			return i;
    	}
    	return -1;
    }
}
